import {reactive, toRaw, watch} from "vue";


export function useList(options) {
    const {page = 1, size = 15, apiFun, params = {}, isLoading = false} = options

    const paramsInit = Object.assign({}, toRaw(params))

    const paging = reactive({
        page,
        size,
        total: 0,
    })

    const result = reactive({
        loading: isLoading,
        list: []
    })

    // 请求分页接口
    const getList = () => {
        result.loading = true
        return apiFun({
            page: paging.page,
            page_size: paging.size,
            ...params
        })
            .then((res) => {
                paging.total = res?.total
                result.list = res?.list
                return Promise.resolve(res)
            })
            .catch((err) => {
                return Promise.reject(err)
            })
            .finally(() => {
                result.loading = false
            })
    }

    watch(
        () => paging.page,
        () => getList()
    )
    watch(
        () => paging.size,
        () => getList()
    )

    // 重置为第一页
    const search = () => {
        paging.page = 1
        getList()
    }
    // 重置参数
    const resetSearch = () => {
        Object.keys(paramsInit).forEach((item) => {
            params[item] = paramsInit[item]
        })
        paging.page = 1
        getList()
    }

    return {
        paging,
        result,
        getList,
        search,
        resetSearch
    }
}